package com.qn.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 功能描述
 *
 * @author w30009430
 * @since 2023 -09-05 12:03
 */
@Slf4j
public class I18nUtils {

    /**
     * Gets i 18 n error msg.
     *
     * @param code          the code
     * @param supplementMsg the supplement msg
     * @param language      the language
     * @return the i 18 n error msg
     */
    public static String getI18nErrorMsg(int code, String supplementMsg, String language) {
        String key = "error." + code;
        String message = getMsgByLanguage(key, language);
        if (StrUtil.isNotEmpty(message)) {
            message = message + " " + supplementMsg;
        }
        return message;
    }

    private static String getMsgByLanguage(String key, String language) {
        String country = getCountryByLanguage(language);

        ResourceBundle bundle = null;
        String value = null;

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        return getMsg(key, language, country, value, contextClassLoader);
    }

    private static String getMsg(String key, String language, String country, String value, ClassLoader contextClassLoader) {
        ResourceBundle bundle;
        try {
            if (contextClassLoader != null) {
                bundle = ResourceBundle.getBundle("i18/messages", new Locale(language, country), contextClassLoader);
            } else {
                bundle = ResourceBundle.getBundle("i18/message", new Locale(language, country));
            }

            if (bundle != null) {
                value = bundle.getString(key);
            }
        } catch (MissingResourceException var8) {
            log.error("missing resource error !");
        }

        return value;
    }


    private static String getCountryByLanguage(String language) {
        String country = "us";
        if ("zh".equals(language)) {
            country = "cn";
        }

        return country;
    }

    public static String getMsgByErrorCode(int code) {
        ClassLoader classLoader = null;
        if (code > 10000) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }

        String key = "error." + code;

        String language = CookieUtil.getLanguage();

        String country = CookieUtil.getCountry();
        String value = null;

        return getMsg(key, language, country, value, classLoader);
    }
}

